﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Timers;
using AllInOne.Models;
using AllInOne.Entity;
using PropertyChanged;
using AllInOne.HDI.CRT_591_M001;

namespace AllInOne.MainPages
{
    /// <summary>
    /// 获取发卡信息页面--手动发卡
    /// </summary>
    [AddINotifyPropertyChangedInterface]
    public partial class GiveCard_Page_InPlant : Page
    {

        
        private MainWindow parent;

        private Timer tipsTimer;

        private UInt32 Hdle = 0;
        

        public GiveCard_Page_InPlant()
        {
            InitializeComponent();
        }

        public GiveCard_Page_InPlant(MainWindow parent)
        {
            InitializeComponent();
            this.parent = parent;
            this.InitTimer();
            this.Hdle = this.parent.Hdle;
        }


        private void BtnBackToIndex_MouseUp(object sender, MouseButtonEventArgs e)
        {
            this.parent.ResetIndex();
        }

     
        /// <summary>
        /// 得到身份证信息
        /// </summary>
        public void InitPage()
        {

            //this.imgTitle.Source = new BitmapImage(new Uri(this.parent.enterBusinessInfo.getImgTitleUrl()));
        }

        private int  photoIndex = 0;
        private int interval = 2;
        private int stay = 5;

        public void InitTimer()
        {
            this.tipsTimer = new Timer();
            this.tipsTimer.Interval = 100;
            this.tipsTimer.Elapsed += new ElapsedEventHandler(delegate (object sender, ElapsedEventArgs e)
            {

                photoIndex++;
                int step = 1;
                if (photoIndex > 0 && photoIndex < 4 * interval)
                {
                    step = photoIndex / interval + 1;
                }
                else
                {
                    step = 5;
                    if (photoIndex > stay + 4 * interval)
                    {
                        photoIndex = 0;
                    }
                }

                //this.Dispatcher.Invoke(new Action(delegate ()
                //{
                //    this.imgTips.Source = new BitmapImage(new Uri(string.Format("pack://application:,,,/images/put_id{0}.png", step)));
                //}));


            });
            this.tipsTimer.Enabled = false;
        }

        public void StartTimer() {
            this.tipsTimer.Enabled = true;

            this.photoIndex = 0;
            Console.WriteLine("播放声音：请将您的居民二代身份证放置在感应区域。");
            this.parent.PlaySound(Properties.Resources.male_put_id, Properties.Resources.female_put_id);
        }


        public void StopTimer()
        {
            this.tipsTimer.Enabled = false;
        }

        private void 测试_Click(object sender, RoutedEventArgs e)
        {

        }

        private void BtnConfirm_MouseUp(object sender, MouseButtonEventArgs e)
        {
            //1. 需要做一层验证，就是此车号在不在此备案信息下面，如果是硫酸的话。



            //01先判断是不是
            if (tb_InputPlate.Text != "" && (tb_InputPlate.Text.Length != 7 && tb_InputPlate.Text.Length != 8))
            {
                MessageBox.Show("车牌号位数不对,不能提交！");
                return;
            }
            T_Dictionary Model_1 = (T_Dictionary)cb_company.SelectedItem;
            T_Dictionary Model_2 = (T_Dictionary)cb_position.SelectedItem;
            T_Dictionary Model_3 = (T_Dictionary)cb_goods.SelectedItem;

            //卡号：AY130911049
            string ICardNum = "AY130911050";
            string RegName = tb_DriverName.Text;
            string IdentityNum = "410325199001010051";
            int OpType = 1;
            string Company = Model_1.DictItemValue;
            string Position = Model_2.DictItemValue;
            string GoodsName = Model_3.DictItemValue;
            string Plate = tb_InputPlate.Text;

            T_RegisterInfo obj = new T_RegisterInfo();
            obj.ICardNum = ICardNum;
            obj.RegName = RegName;
            obj.IdentityNum = IdentityNum;
            obj.OpType = OpType;
            obj.Company = Company;
            obj.Position = Position;
            obj.GoodsName = GoodsName;
            obj.CardStatus = 1;//此个状态最开始设置成0,并且序列号字段有值，修改完之后将序列号字段修改为加上发卡时间的形式
            obj.Plate = Plate;
            obj.ReceiveTime = System.DateTime.Now;
            obj.Guid = System.Guid.NewGuid().ToString();
            int order = 1;
            obj.OrderNumber = GenOrderNumber(order);


            //01 验证信息是否全
            if (!CheckInputData())
            {
                MessageBox.Show("信息不完整不能提交！");
            }

            //02 硫酸的数据--进行校验--根据备案号信息
            if (GoodsName == "硫酸")
            {
                string strYNumber = "Y15220022878183";
                string msg1 = "";
                //检查这个车牌的车能否拉这些数据，
                if (!ServiceWebApi.CheckSulphuricAcid(Plate, strYNumber,out msg1))
                {
                    MessageBox.Show("信息有误" + msg1);
                }
                //else
                //{
                //    MessageBox.Show("数据保存--成功");
                //}
            }

            //03 IC卡信息，这个是两步的操作，如何写成一个操作，肯定是数据录入成功了，然后进行发卡，但是
            //提示信息如何展示

            //string ICardNum, string RegName, string IdentityNum, string OpType, string Company, string Position, string GoodName, string Plate
            //02 数据保存到数据库 AddRegisterInfo
            
            //存身份证号加密码存储---
            if (!ServiceWebApi.AddRegisterInfo(obj))
            {
                MessageBox.Show("数据保存--失败");
            }
            else
            {
                //成功之后
                //-测试-----------------------------------------------------------------
                order++;

                //序列号
                //展示,并且后面的还要继续

                MessageBox.Show("数据保存--成功");
            }


            //弹出序列号:9位，组成



            #region IC卡-发卡-相关操作

            //连接发卡机
            this.parent.ShowText("开始发卡1");

            string strState = "";

            string UID="";


            string msg;
            if (GrantCardClient.MoveCardToRF(Hdle, "00", out msg))
            {
                strState += "移卡到RF位成功;";
                //读取卡号--激活
                if (GrantCardClient.MiCardActivate(Hdle, "00", out UID, out msg))
                {
                    strState += "读取卡号成功,卡号：" + UID + ";";
                }
                else
                {
                    //失败--记录下来
                    strState += "读取卡号失败：" + msg + ";";
                }

                //下电释放--下电
                if (GrantCardClient.MiCardDactivate(Hdle, "00", out msg))
                {
                    strState += "下电释放成功;";
                }
                else
                {
                    strState += "下电释放失败;";
                }

                //移动卡到卡口位置
                //移动卡操作：前端不持卡位 (UInt32 Hdle, string AddrComb, out string msg)
                if (GrantCardClient.MoveCardToFront1(Hdle, "00", out msg))
                {
                    //移到这里，则发卡成功了
                    strState += "移动卡操作：前端不持卡位, 发卡成功;";
                }
                else
                {
                    strState += "发卡失败" + msg;
                }
            }
            else
            {
                //据据状态码进行提示错误
                MessageBox.Show("移卡到RF位失败");
            }

            //更新数据库将发卡的卡号更新上去
            if (UID != "")
            {
                //
            }
            else
            {
                MessageBox.Show("发卡失败--具体原因还要进行一步排查");
            }
            //开始推卡到出口，还要明白发完卡，需不需要判断卡是否被取走
            //发完卡后，提供一个查询卡信息，
            #endregion
        }

        /// <summary>
        /// 生成发卡序列号
        /// </summary>
        /// <returns></returns>
        private string GenOrderNumber(int order)
        {
            //序列号格式：自助机号1位 + 月日4位 + 序号4位
            //例如：107070001
            string OrderNumber = "";
            OrderNumber = MainWindow.AllInOneSerialNumber + System.DateTime.Now.ToString("MMdd") + order.ToString().PadLeft(4, '0');
            return OrderNumber;
        }


        private bool CheckInputData()
        {
            try
            {
                bool check = true;
                string msg = "";
                if (tb_DriverName.Text == ""|| tb_DriverName.Name == "XXX")
                {
                    msg += "司机名字为空;";
                    check = false;
                }
                if (tb_InputPlate.Text == "" || tb_InputPlate.Name == "XXXXXXX")
                {
                    msg += "车牌号为空;";
                    check = false;
                }
                T_Dictionary GoodsModel = (T_Dictionary)cb_goods.SelectedItem;
                if (GoodsModel.DictItemValue == "")
                {
                    msg += "货物为空;";
                    check = false;
                }
                //后续继续添加------
                return check;
            }
            catch (Exception ex)
            {
                SimpleConsole.WriteInfo("入厂制卡-信息录入-录入基础信息验证-异常" + ex.ToString(), this);
                return false;
            }
        }

        private void Test_Btn1_Click(object sender, RoutedEventArgs e)
        {
            #region 自动生成 初始化信息
            //#region 初始化公司信息
            //List<Company> dl = new List<Company>();
            //for (int i = 0; i < 5; i++)
            //{
            //    Company temp = new Company();
            //    temp.guid = System.Guid.NewGuid().ToString("N");
            //    temp.code = (i + 1).ToString();
            //    temp.value = "公司" + (i + 1).ToString();
            //    dl.Add(temp);
            //}

            //cb_company.ItemsSource = dl;
            //cb_company.DisplayMemberPath = "value";
            //cb_company.SelectedValuePath = "guid";
            //#endregion

            //#region 初始化位置信息
            //List<Company> positionList = new List<Company>();
            //for (int i = 0; i < 5; i++)
            //{
            //    Company temp = new Company();
            //    temp.guid = System.Guid.NewGuid().ToString("N");
            //    temp.code = (i + 1).ToString();
            //    temp.value = "位置" + (i + 1).ToString();
            //    positionList.Add(temp);
            //}
            //cb_position.ItemsSource = positionList;
            //cb_position.DisplayMemberPath = "value";
            //cb_position.SelectedValuePath = "guid";
            //#endregion

            //#region 初始化货物信息
            //List<Company> goodsList = new List<Company>();
            //for (int i = 0; i < 50; i++)
            //{
            //    Company temp = new Company();
            //    temp.guid = System.Guid.NewGuid().ToString("N");
            //    temp.code = (i + 1).ToString();
            //    temp.value = "货物" + (i + 1).ToString();
            //    goodsList.Add(temp);
            //}
            //cb_goods.ItemsSource = goodsList;
            //cb_goods.DisplayMemberPath = "value";
            //cb_goods.SelectedValuePath = "guid";
            //#endregion
            #endregion

            if (!InitLoadData())
            {
                MessageBox.Show("基础信息加载失败");
            }
        }

        private bool InitLoadData()
        {
            try
            {
                //List<T_Dictionary> list = ServiceWebApi.GetDicByType("Company,Position,Goods");

                //if (list != null)
                //{
                //    #region 初始化公司信息
                //    cb_company.ItemsSource = list.FindAll(p => p.ParentCode == "Company");
                //    cb_company.DisplayMemberPath = "DictItemValue";
                //    cb_company.SelectedValuePath = "Id";
                //    #endregion

                //    #region 初始化位置信息
                //    cb_position.ItemsSource = list.FindAll(p => p.ParentCode == "Position");
                //    cb_position.DisplayMemberPath = "DictItemValue";
                //    cb_position.SelectedValuePath = "Id";
                //    #endregion

                //    #region 初始化货物信息
                //    cb_goods.ItemsSource = list.FindAll(p => p.ParentCode == "Goods");
                //    cb_goods.DisplayMemberPath = "DictItemValue";
                //    cb_goods.SelectedValuePath = "Id";
                //    #endregion
                //}


                List<T_Dictionary> list = ServiceWebApi.GetDicByType("Company,Position,Goods");

                if (list != null)
                {
                    #region 初始化公司信息
                    cb_company.ItemsSource = list.FindAll(p => p.ParentCode == "Company");
                    cb_company.DisplayMemberPath = "DictItemValue";
                    cb_company.SelectedValuePath = "Id";
                    #endregion

                    #region 初始化位置信息
                    cb_position.ItemsSource = list.FindAll(p => p.ParentCode == "Position");
                    cb_position.DisplayMemberPath = "DictItemValue";
                    cb_position.SelectedValuePath = "Id";
                    #endregion

                    #region 初始化货物信息
                    cb_goods.ItemsSource = list.FindAll(p => p.ParentCode == "Goods");
                    cb_goods.DisplayMemberPath = "DictItemValue";
                    cb_goods.SelectedValuePath = "Id";
                    #endregion
                }

                SimpleConsole.WriteInfo("入厂制卡-信息录入-加载基础信息-完成", this);
                return true;
            }
            catch (Exception ex)
            {
                SimpleConsole.WriteInfo("入厂制卡-信息录入-加载基础信息-异常"+ ex.ToString(), this);
                return false;
            }
        }

        /// <summary>
        /// 根据选的是什么来进行处理
        /// 两个兼有都行，目前保留
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Cb_goods_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                //string strGoods = cb_goods.SelectedValue.ToString();
                T_Dictionary GoodsModel = (T_Dictionary)cb_goods.SelectedItem;
                
                if (GoodsModel != null && GoodsModel.DictItemValue == "硫酸")
                {
                    //弹出需要选择备案号信息
                    MessageBox.Show("请选择备案号信息");
                    row50_Number.Visibility = Visibility.Visible;
                    row51_Number.Visibility = Visibility.Visible;
                }
                else
                {
                    row50_Number.Visibility = Visibility.Hidden;
                    row51_Number.Visibility = Visibility.Hidden;
                }
            }
            catch (Exception ex )
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void BtnInputPlate_MouseUp(object sender, MouseButtonEventArgs e)
        {
            //this.parent.ShowModifyPhone();
            //方法一：嵌入到页面里面的选择页
            //this.parent.ShowPlateInPut();

            //方法二：弹出来的页面
            ShowInputPlateWinDialog();
            //if (authModel != null)
            //{
            //    MessageBox.Show("录入车牌号信息成功:" + authModel.AuthCode);           
            //}
            //else
            //{
            //    MessageBox.Show("录入车牌号信息出错");
            //}
        }

        /// <summary>
        /// 弹出输入车牌号窗体并返回值
        /// </summary>
        /// <returns></returns>
        private void ShowInputPlateWinDialog()
        {
            string oldPlatt = "";
            if (tb_InputPlate.Text == "XXXXXXX")
            {
                oldPlatt = "";
            }
            else
            {
                oldPlatt = tb_InputPlate.Text;
            }
            //PlateInputWindow plateInputWindow = new PlateInputWindow(oldPlatt);
            PlateInputWin plateInputWindow = new PlateInputWin(oldPlatt);
            plateInputWindow.DlgDialogEvent_InputPlate -= new DlgDialog(this.DlgDialogEvent_InputPlate_AuthBack);
            plateInputWindow.DlgDialogEvent_InputPlate += new DlgDialog(this.DlgDialogEvent_InputPlate_AuthBack);
            //弹框居中
            plateInputWindow.ShowInTaskbar = false;
            plateInputWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            plateInputWindow.Show();
        }

        private void DlgDialogEvent_InputPlate_AuthBack(string plateNumber)
        {
            if (!string.IsNullOrEmpty(plateNumber))
            {
                //将车牌号反填过来
                tb_InputPlate.Text = plateNumber;
                BtnInputPlate.Content = "点击修改车牌";
            }
            else
            {
                MessageBox.Show("录入车牌号信息不能为空");
            }
        }

        private void BtnInputPlate_Click(object sender, RoutedEventArgs e)
        {
            ShowInputPlateWinDialog();
            //MessageBox.Show("录入车牌号信息");//最好出个信息
            //PlateEdit plateEdit = new PlateEdit();
            //plateEdit.DlgDialogEvent_InputPlate -= new DlgDialog(this.DlgDialogEvent_InputPlate_AuthBack);
            //plateEdit.DlgDialogEvent_InputPlate += new DlgDialog(this.DlgDialogEvent_InputPlate_AuthBack);
            //plateEdit.ShowDialog();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //01 初始化信息
            InitLoadData();

        }
        public void SetPlate(string Plate)
        {
            if (!string.IsNullOrEmpty(Plate))
            {
                tb_InputPlate.Text = Plate;
            }
        }




        public void SetYNumber(string YNumber)
        {
            if (!string.IsNullOrEmpty(YNumber))
            {
                tb_PutOnRecordNum.Text = YNumber;
            }
        }

        private void BtnInputPutOnRecordNum_MouseUp(object sender, MouseButtonEventArgs e)
        {
            InputPutOnRecordNum();
        }

        private void BtnInputPutOnRecordNum_MouseUp(object sender, RoutedEventArgs e)
        {
            InputPutOnRecordNum();
        }
        private void InputPutOnRecordNum()
        {
            MessageBox.Show("请输入备案号");
            string strYNumbe = "";
            //显示备案号输入
            this.parent.ShowPutOnRecordInPut(strYNumbe);
        }

        private void BtnInputPlate_Click_1(object sender, RoutedEventArgs e)
        {

        }
    }
}
